import {
  http
} from '@/common/http';
import {
  queryStringify,
  isEmpty,
  debounce,
  checkType,
  getProvider
} from "@/common/util.js";
// 获取商户信息
export function getPayInfo(data = {}) {
  return http("/trade/view/getPayInfo", data, {
    service: 'iassbff'
  })
}

// 发票联想
export function queryByTitle(data = {}) {
  return http("/trade/view/queryByTitle", data, {
    service: 'iassbff',
    loading: false
  })
}

// 下单
export function createOrder(data = {}) {
  return http("/trade/view/createOrder", data, {
    service: 'iassbff',
  })
}

// 关闭订单
export function closeOrder(data = {}) {
  return http("/trade/view/closeOrder", data, {
    service: 'iassbff',
  })
}

//查询是否有开票功能 来决定是否展示开票按钮
export function getConfig(data = {}) {
  return http("/trade/view/getConfig", data, {
    service: 'iassbff',
  })
}
// 查询发票类型
export function getMchInvoiceInfo(data = {}) {
  return http("/trade/view/getMchInvoiceInfo", data, {
    service: 'iassbff',
  })
}

// 开票
export function saveInvoice(data = {}) {
  return http("/trade/view/saveInvoice", data, {
    service: 'iassbff',
  })
}

// 备注选项模糊查询--返回值加一层判断
export function queryRemarkOptions(data = {}) {
  return http("/trade/view/queryRemarkOptions", data, {
    service: 'iassbff',
  })
}
// 获取手机好吗-美好生活收单券
export function getPhoneNumber(data = {}) {
  return http("/trade/view/getPhoneNumber", data, {
    service: 'iassbff',
  })
}
// 计算优惠金额
export function calcPaymentAmt(data = {}) {
  return http("/trade/view/calcPaymentAmt", data, {
    service: 'iassbff',
    goError: false
  })
}
export async function callPayment(data, callback = "") {
  let callbackIsFunction = checkType(callback) === 'function';
  let providerData = await getProvider('payment');
  let payData = {
    provider: providerData.provider[0],
  };
  if (payData.provider == 'alipay') {
    payData.orderInfo = (data.thirdOrderNo || '').slice(2);
  } else {
    payData.timeStamp = data.timeStamp || '';
    payData.nonceStr = data.nonceStr || '';
    payData.signType = data.signType || '';
    payData.paySign = data.paySign || '';
    payData.package = data.package || data.packageData;
  }
  uni.requestPayment({
    ...payData,
    success: (res) => {
      res.paycode = 1
      if (payData.provider == 'alipay' && res.resultCode != '9000') {
        res.paycode = res.resultCode == '6001' ? 2 : 3
      }
      let payRes = {
        result: res,
        param: data
      }
      if (callbackIsFunction) {
        callback(payRes)
      } else {
        goResult(payRes)
      }
    },
    fail: (err) => {
      let isCancel = err.errMsg.indexOf('cancel') > 0 || err.resultCode == '6001';
      err.paycode = isCancel ? 2 : 3;
      let payRes = {
        result: err,
        param: data
      }
      if (callbackIsFunction) {
        callback(payRes)
      } else {
        goResult(payRes)
      }
    }
  })
}

function goResult(res) {
  let {
    result,
    param
  } = res;
  let data = {
    paycode: result.paycode,
    totalFee: param.totalFee,
    shopName: param.cnAbber,
    orderNo: param.orderNo,
    mchntCd: param.mchntCd,
    mchOriginalId: param.mchOriginalId,
    mchType: param.mchType
  }
  let query = queryStringify(data)
  wx.redirectTo({
    url: `/pages/iassCashier/payRes${query}`,
  })
}
// 使用逆地理编码 API 获取省份和城市信息
export function getAddressByLatAndLon(latitude, longitude) {
  return new Promise((resolve, reject) => {
    if (isEmpty(latitude) || isEmpty(longitude)) {
      reject({
        statusCode: 2,
        errMsg: '参数错误，不能为空'
      })
      return
    }
    uni.request({
      url: 'https://api.map.baidu.com/reverse_geocoding/v3',
      data: {
        ak: 'YO3hukOUzXuBcC8Khuh9OQNAfpOpSxiO', // 替换为自己申请的百度地图开放平台的密钥（AK）
        output: 'json',
        coordtype: 'wgs84ll', // 输入的坐标类型，与上面获取的经纬度类型一致
        location: latitude + ',' + longitude
      },
      success: (locaRes) => {
        if (locaRes.statusCode === 200) {
          if (locaRes.data.status === 0) {
            resolve(locaRes.data.result)
          } else {
            reject({
              statusCode: locaRes.data.status,
              errMsg: '获取地理位置信息失败'
            })
          }
        } else {
          reject(locaRes)
        }
      },
      fail: (error) => {
        reject(error)
      }
    })
  })
}